<template>

  <div>
		<div class="screen-box">
			<div class="query-box">
				<!-- <span>场景</span>
				<el-select v-model="queryInfo.type" placeholder="全部客户" size="medium" class="button-item">
					<el-option
						v-for="item in typeOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value">
					</el-option>
				</el-select> -->
				<el-input placeholder="搜索客户" v-model="queryInfo.search" class="select-item" size="medium" clearable>
					<!-- <el-button slot="append" icon="el-icon-search"></el-button> -->
				</el-input>
				
				<el-select v-model="queryInfo.grade" placeholder="客户等级" size="medium" class="select-item">
					<el-option
						label="所有等级"
						:value="null">
					</el-option>
					<el-option
						v-for="item in gradeOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
				<el-select v-model="queryInfo.platform" placeholder="客户平台" size="medium" class="select-item">
					<el-option
						label="全部平台"
						:value="null">
					</el-option>
					<el-option
						v-for="item in platformOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
				<el-button type="primary" class="button-item" size="medium" @click="searchBtn">查询</el-button>
			</div>
			<div class="button-box">
				<el-button type="primary" class="button-item" size="medium" @click="addBtn">添加客户</el-button>
				<el-button type="primary" class="button-item" size="medium" @click="delAllBtn">删除客户</el-button>
				<el-upload
				  class="el-upload-box"
				  action="/base/api/v1/customer/manage/import/"
					name="file"
					accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
					:show-file-list="false"
					:on-success="handleUploadSuccess"
					:before-upload="handleBeforeUpload">
				  <el-button type="primary" class="button-item" size="medium">导入客户</el-button>
				</el-upload>
				<el-button type="primary" class="button-item" size="medium" @click="exportBtn">导出客户</el-button>
			</div>
		</div>
		
		<el-table
		  ref="customerFormRef"
		  v-loading="loading"
			:stripe="false"
			size="small"
			:data="tableData"
			tooltip-effect="dark"
			style="width: 100%;"
			:header-cell-style="{
			'font-weight': 'bold',
			'color': '#666666',
			'font-size': '18',
			'background-color': '#f8f8f9'}"
      border>
			<el-table-column
				type="selection"
				width="55">
			</el-table-column>
      <el-table-column
      		prop="name"
      		label="客户名"
      		min-width="100">
      </el-table-column>
      <el-table-column
      		prop="nickname"
      		label="称呼"
      		min-width="100">
      </el-table-column>
			<el-table-column
					prop="wechat"
					label="微信"
					min-width="100">
			</el-table-column>
			<el-table-column
					prop="qq"
					label="QQ"
					min-width="100">
			</el-table-column>
			<el-table-column
					prop="telephone"
					label="电话"
					min-width="100">
			</el-table-column>
			<el-table-column
					prop="address_code"
					label="地址"
					min-width="100">
					<template slot-scope="scope">
						<span>{{ formatAddress(scope.row.address_code) }}</span>
					</template>
			</el-table-column>
			<el-table-column
					prop="grade_label"
					label="等级"
					min-width="100">
			</el-table-column>
			<el-table-column
					prop="platform_label"
					label="客户平台"
					min-width="100">
			</el-table-column>
			<el-table-column
					prop="joined_time"
					label="创建时间"
					min-width="100">
			</el-table-column>


			<el-table-column label="操作" width="120" fixed="right" header-align="center" align="center">
				<template slot-scope="scope">
          <el-button
            type="text"
          	size="small"
          	@click="editBtn(scope.$index, scope.row)">编辑</el-button>
          <el-button
            type="text"
          	size="small"
          	@click="delBtn(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="page-box">
			<el-pagination
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:current-page.sync="queryInfo.page"
			background
			layout="total, sizes, prev, pager, next"
			:total="count"
			:page-size="queryInfo.page_size"
			:page-sizes="limitList">
			</el-pagination>
    </div>
		
		<Form ref="customerFormDialogRef" @reloadTable="getDataList" />
		
		<ExportDialog ref="exportDialogRef" />

  </div>

</template>

<script>
import { mapGetters } from 'vuex'
import { getCustomerList, delCustomer } from '@/api/customer'
import Form from './form'
import ExportDialog from './export_dialog'
import { CodeToText } from 'element-china-area-data'

export default {
	computed: {
	  ...mapGetters([
	    "gradeOptions",
	    "platformOptions",
	  ])
	},
	components: {
	  Form,
		ExportDialog,
	},
	data () {
		return {
			// 加载
			loading: false,
			// 表格数据
			tableData: [],
			// 总数据条数
			count: 0,

			// 允许的每页条数列表
			limitList: [10, 15, 35, 50],

			// get请求携带参数
			queryInfo: {
				// 每页条数
				page_size: 10,
				// 当前页码
				page: 1,
				// 客户等级
				grade: null,
				// 客户平台
				platform: null,
				// 全局搜索
				search: "",
			},
		}
  },
	// 生命周期，实例创建完成后执行
  created () {
    // 获取后台数据
    this.getDataList()
  },
  methods: {
		// 地区编码 转 地区名称
		formatAddress(value) {
			if (!value) {
				return ""
			}
			let province = CodeToText[value[0]]
			let city = CodeToText[value[1]]
			let area = CodeToText[value[2]]
			let address = province + " " + city + " " + area
			return address
		},
    // 获取列表数据
    getDataList () {
      this.loading = true
      // 调用封装好的API
      getCustomerList(this.queryInfo).then(response => {
				// console.log(response.data)
        this.tableData = response.data
        this.count = response.count
				this.loading = false

      }).catch(error => {
        console.log(error)
				this.loading = false
      })
    },
    // 监听 每页数据 变化
    handleSizeChange (val) {
      this.queryInfo.page_size = val
      this.getDataList()
    },
    // 监听 页码 变化
    handleCurrentChange (val) {
      this.queryInfo.page = val
      this.getDataList()
    },
    // 编辑
    editBtn (index, row) {
      this.$refs.customerFormDialogRef.dialogVisible = true
      this.$refs.customerFormDialogRef.isAdd = false
			this.$refs.customerFormDialogRef.form = JSON.parse(JSON.stringify(row))
    },
		// 查询
		searchBtn(evt) {
			this.$initBtnStatus(evt)
			this.queryInfo.page = 1
			this.getDataList()
		},
    // 删除
    delBtn (index, row) {
      this.$confirm('此操作将会永久删除数据, 是否继续?', '提示', {
      	confirmButtonText: '确定',
      	cancelButtonText: '取消',
      	type: 'warning',
      	center: true
      }).then(() => {
        let ids = [row.id]
        delCustomer({"ids": ids}).then(res => {
          this.$successMsg("删除成功")
          this.getDataList()
        }).catch(() => {
        })
      }).catch(() => {
      })
    },
		delAllBtn (evt) {
			this.$initBtnStatus(evt)
			let ids = []
			let rows = this.$refs.customerFormRef.selection
			for (let i in rows) {
				ids.push(rows[i].id)
			}
			if (ids.length == 0) return this.$errorMsg("未选择数据")
			this.$confirm('此操作将会永久删除数据, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			}).then(() => {
			  delCustomer({"ids": ids}).then(res => {
			    this.$successMsg("删除成功")
			    this.getDataList()
			  }).catch(() => {
			  })
			}).catch(() => {
			})
		},
		// 添加客户
		addBtn (evt) {
			this.$initBtnStatus(evt)
			this.$refs.customerFormDialogRef.dialogVisible = true
			this.$refs.customerFormDialogRef.isAdd = true
		},
		// 上传成功处理
		handleUploadSuccess(res, file) {
			// console.log(res)
			if (res.code != 200) {
				 this.$errorMsg(res.message)
			} else {
				this.$successMsg(res.message)
			}
		},
		// 上传前操作
		handleBeforeUpload(file) {
		  const type = (file.type === 'application/vnd.ms-excel') | (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		  const size = file.size / 1024 / 1024 < 10;
		
			if (!type) {
				this.$errorMsg('上传文件格式错误！')
			}
			if (!size) {
				this.$errorMsg('上传文件大小不能超过 10MB!')
			}
			return type && size;
		},
		// 导出操作
		exportBtn (evt) {
			this.$initBtnStatus(evt)
			this.$refs.exportDialogRef.dialogVisible = true
			this.$refs.exportDialogRef.tableData = this.tableData
		}
  }
}
</script>

<style lang="scss" scoped>

  .page-box {
    text-align: right;
    margin-top: 20px;
  }
	
	.screen-box {
		margin-bottom: 20px;
		overflow: hidden;
		
		.query-box {
			float: left;
		}
		
		.button-box {
			float: right;
		}
		
		.button-item {
			width: 100px;
			margin-right: 10px;
			margin-left: 0;
		}
		
		.select-item {
			width: 150px;
			margin-right: 10px;
			margin-left: 0;
		}
		
		.el-upload-box {
			display: inline-block;
		}
	}

</style>
